/**
 * 创建线性渐变
 * @param {*} ctx canvas上下文
 * @param {*} node 节点
 * @param {*} linearGradient 线性渐变配置对象
 */
export const createLinearGradient = (ctx, node, linearGradient) => {
  if (!linearGradient || linearGradient.visible === false) return;
  const { width, height } = node;
  const { angle = 0, colorStops = [] } = linearGradient;
  const center = { x: width / 2, y: height / 2 };
  // 渐变角度
  const radian = angle * (Math.PI / 180);
  // 计算线性渐变长度
  const gradientLineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
  const startX = center.x - Math.sin(radian) * (gradientLineLength / 2);
  const startY = center.y + Math.cos(radian) * (gradientLineLength / 2);
  const endX = center.x + Math.sin(radian) * (gradientLineLength / 2);
  const endY = center.y - Math.cos(radian) * (gradientLineLength / 2);
  // 获取渐变对象
  const gradient = ctx.createLinearGradient(startX, startY, endX, endY);
  // 添加由偏移值和颜色值指定的断点到渐变
  colorStops?.forEach(({ offset, color }) => gradient.addColorStop(offset, color));
  return gradient;
};

/**
 * 创建径向渐变
 * @param {*} ctx canvas上下文
 * @param {*} node 节点
 * @param {*} radialGradient 径向渐变配置对象
 */
export const createRadialGradient = (ctx, node, radialGradient) => {
  if (!radialGradient || radialGradient.visible === false) return;
  const { width, height } = node;
  const center = { x: width / 2, y: height / 2 };
  const { c0 = center, r0 = 0, c1 = center, r1 = Math.max(width / 2, height / 2), colorStops = [] } = radialGradient;
  // 获取渐变对象
  const gradient = ctx.createRadialGradient(c0.x, c0.y, r0, c1.x, c1.y, r1);
  // 添加由偏移值和颜色值指定的断点到渐变
  colorStops?.forEach(({ offset, color }) => gradient.addColorStop(offset, color));
  return gradient;
};
